var express = require("express");
var router = express.Router();
var db = require("../db/db.js");
const crypto = require("crypto");
var path = require("path");
var moment = require("moment");

// 图片验证码
var svgCaptcha = require("svg-captcha");
// tooken生成与验证
const { jwtSign, jwtCheck } = require("../module/jwt");

function md5(data = "") {
  return crypto.createHash("md5").update(data).digest("hex");
}

// 获取验证码
router.get("/captcha", function (req, res) {
  var captcha = svgCaptcha.create({
    size: 4, // 验证码长度
    ignoreChars: "0oO1iI", // 验证码字符中排除 0o1i
    noise: 1, // 干扰线条的数量
    color: true, // 验证码的字符是否有颜色，默认没有，如果设定了背景，则默认有
    background: "#cc9966", // 验证码图片背景颜色
  });

  req.session.captcha = captcha.text;
  console.log("验证码", req.session.captcha);
  res.type("svg");

  res.status(200).send(captcha.data);
});
// 验证码验证
router.get("/verification", (req, res) => {
  // console.log("chuancna ", req.query, req.session);
  if (
    req.query.code.toLocaleUpperCase() ===
    req.session.captcha.toLocaleUpperCase()
  ) {
    res.jsonp({
      code: 200,
      message: "验证码正确",
    });
  } else {
    res.jsonp({
      code: 400,
      message: "验证码不正确",
    });
  }
});
/* GET home page. */
//获取用户详情
router.get("/userinfo", async (req, res, next) => {
  jwtCheck(req.query.token).then(async (data) => {
    let userinfo = await db.query("select * from user where id=?", [data.id]);
    delete userinfo[0].password;
    if (userinfo) {
      res.jsonp({
        code: 200,
        data: userinfo[0],
      });
    }
  });
});
// 修改密码
router.put("/updatepass", async (req, res, next) => {
  let { username, password, newpassword } = req.body;
  let state = await db.query(
    "select * from user where username=? and password=?",
    [username, password]
  );
  if (state.length > 0) {
    await db
      .query("update user set password=? where username=?", [
        md5(newpassword),
        username,
      ])
      .then((result) => {
        console.log(result);
        var data = {
          code: 200,
          message: "操作成功",
        };
        res.jsonp(data);
      });
  } else {
    var data = {
      code: 200,
      message: "用户名或密码不正确",
    };
    res.jsonp(data);
  }
});

// 删除用户
router.delete("/del", async (req, res, next) => {
  let id = req.query.id;
  data = await db.query("delete from user where id=?", [id]);
  if (data.affectedRows === 1) {
    let data = {
      code: 200,
      message: "删除成功",
    };
    res.jsonp(data);
  } else {
    let data = {
      code: 500,
      message: "删除失败",
    };
    res.jsonp(data);
  }
});

// 注册
router.post("/register", async (req, res, next) => {
  console.log(req.body)
  let { username, password, avatar, nickname } = req.body;
  let user = await db.query("select * from user where username=? or nickname=?", [
    username,
    nickname,
  ]);
  if (user.length > 0) {
    let data = {
      code: 201,
      message: "用户名或昵称已存在",
    };
    res.jsonp(data);
  } else {
    let date=moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
    let result = await db.query(
      "INSERT INTO USER(id,username,PASSWORD,avatar,nickname,createtime,phone) VALUES(NULL,?,?,?,?,?,?);",
      [username, md5(password), avatar, nickname,date,null]
    );
    if (result.affectedRows === 1) {
      let data = {
        code: 200,
        message: "注册成功",
      };
      res.jsonp(data);
    }
  }
});

// 登录接口
router.post("/login", async function (req, res, next) {
  let { username, password } = req.body;
  let data = await db.query(
    "SELECT * FROM USER where username=? and password=?;",
    [username, md5(password)]
  );
  console.log(username, password);
  if (data.length > 0) {
    console.log(data[0].id);
    const token = jwtSign({ id: data[0].id }); // 用引入的jwtSign方法生成token并返回
    var result = {
      code: 200,
      message: "登录成功",
      token,
    };
    res.jsonp(result);
  } else {
    var result = {
      code: 500,
      message: "用户名或密码不正确",
    };
    res.jsonp(result);
  }
});

module.exports = router;
